package com.bw.lib_storage.manager

import android.content.Context
import com.bw.lib_storage.db.AppDataBase
import com.bw.lib_storage.db.DBUtils
import com.bw.lib_storage.db.entity.History
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.util.Date

/**
 * 播放历史记录管理器
 */
object PlayHistoryManager {
    
    private lateinit var historyDao: com.bw.lib_storage.db.dao.HistoryDao
    
    fun init(context: Context) {
        DBUtils.init(context, "video_history.db")
        historyDao = DBUtils.getDB().historyDao()
    }
    
    /**
     * 添加或更新播放历史
     */
    suspend fun addOrUpdateHistory(
        videoId: String,
        title: String,
        coverUrl: String,
        videoUrl: String,
        currentPosition: Long = 0,
        duration: Long = 0,
        content: String = "",
        authorName: String = "",
        userId: String = ""
    ) = withContext(Dispatchers.IO) {
        val existingHistory = historyDao.getHistoryByVideoId(videoId)
        
        val progressPercentage = if (duration > 0) {
            (currentPosition.toFloat() / duration * 100).coerceIn(0f, 100f)
        } else 0f
        
        val isCompleted = progressPercentage >= 95f // 播放进度超过95%认为已完成
        
        val history = if (existingHistory != null) {
            // 更新现有记录
            existingHistory.copy(
                title = title,
                content = content,
                coverUrl = coverUrl,
                videoUrl = videoUrl,
                currentPosition = currentPosition,
                duration = duration,
                progressPercentage = progressPercentage,
                lastPlayTime = Date(),
                authorName = authorName,
                userId = userId,
                playCount = existingHistory.playCount + 1,
                isCompleted = isCompleted
            )
        } else {
            // 创建新记录
            History(
                videoId = videoId,
                title = title,
                content = content,
                coverUrl = coverUrl,
                videoUrl = videoUrl,
                currentPosition = currentPosition,
                duration = duration,
                progressPercentage = progressPercentage,
                lastPlayTime = Date(),
                queryTime = Date(),
                authorName = authorName,
                userId = userId,
                playCount = 1,
                isCompleted = isCompleted
            )
        }
        
        historyDao.insert(history)
    }
    
    /**
     * 更新播放进度
     */
    suspend fun updatePlayProgress(
        videoId: String,
        currentPosition: Long,
        duration: Long
    ) = withContext(Dispatchers.IO) {
        val history = historyDao.getHistoryByVideoId(videoId)
        if (history != null) {
            val progressPercentage = if (duration > 0) {
                (currentPosition.toFloat() / duration * 100).coerceIn(0f, 100f)
            } else 0f
            
            val isCompleted = progressPercentage >= 95f
            
            val updatedHistory = history.copy(
                currentPosition = currentPosition,
                duration = duration,
                progressPercentage = progressPercentage,
                lastPlayTime = Date(),
                isCompleted = isCompleted
            )
            
            historyDao.updateHistory(updatedHistory)
        }
    }
    
    /**
     * 获取所有播放历史
     */
    suspend fun getAllHistory(): List<History> = withContext(Dispatchers.IO) {
        historyDao.getAllHistory()
    }
    
    /**
     * 获取指定视频的播放历史
     */
    suspend fun getHistoryByVideoId(videoId: String): History? = withContext(Dispatchers.IO) {
        historyDao.getHistoryByVideoId(videoId)
    }
    
    /**
     * 获取最近的播放历史
     */
    suspend fun getRecentHistory(limit: Int = 20): List<History> = withContext(Dispatchers.IO) {
        historyDao.getRecentHistory(limit)
    }
    
    /**
     * 获取未完成的播放历史
     */
    suspend fun getIncompleteHistory(): List<History> = withContext(Dispatchers.IO) {
        historyDao.getIncompleteHistory()
    }
    
    /**
     * 删除指定视频的播放历史
     */
    suspend fun deleteHistoryByVideoId(videoId: String) = withContext(Dispatchers.IO) {
        historyDao.deleteByVideoId(videoId)
    }
    
    /**
     * 清空所有播放历史
     */
    suspend fun clearAllHistory() = withContext(Dispatchers.IO) {
        historyDao.deleteAllHistory()
    }
    
    /**
     * 搜索播放历史
     */
    suspend fun searchHistory(keyword: String): List<History> = withContext(Dispatchers.IO) {
        historyDao.getHistoryByTitle(keyword)
    }
}
